// 首先添加需要的imports
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';

function Shang() {
  const { id } = useParams();
  const [file, setFile] = useState(null);
  const [title, setTitle] = useState('');
  const [cover, setCover] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadStatus, setUploadStatus] = useState('');
  const [videoData, setVideoData] = useState(null);
  const [isDragging, setIsDragging] = useState(false);
  const [isPaused, setIsPaused] = useState(false); // 上传暂停状态
  const [uploadCancelToken, setUploadCancelToken] = useState(null); // 取消令牌
  const [resumeData, setResumeData] = useState(null); // 用于断点续传的数据
  const fileInputRef = useRef(null);
  const coverInputRef = useRef(null);
  const uploadAreaRef = useRef(null);

  // 根据id获取视频数据
  useEffect(() => {
    if (id) {
      const fetchVideoData = async () => {
        try {
          const res = await axios.get(`http://localhost:3005/api/jjk/shi/${id}`);
          if (res.data.code === 200) {
            setVideoData(res.data.data);
            setTitle(res.data.data.title);
          }
        } catch (err) {
          console.error('获取视频数据失败:', err);
        }
      };

      fetchVideoData();
    }
  }, [id]);

  // 处理文件选择
  const handleFileChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      const selectedFile = e.target.files[0];
      setFile(selectedFile);
      if (!title) {
        setTitle(selectedFile.name.replace(/\.[^/.]+$/, ''));
      }
    }
  };

  // 处理封面图片选择
  const handleCoverChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      setCover(e.target.files[0]);
    }
  };

  // 添加拖拽事件处理
  const handleDragOver = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      const droppedFile = e.dataTransfer.files[0];
      if (droppedFile.type.startsWith('video/')) {
        setFile(droppedFile);
        if (!title) {
          setTitle(droppedFile.name.replace(/\.[^/.]+$/, ''));
        }
      } else {
        alert('请上传视频文件');
      }
    }
  };

  // 删除重复的状态变量声明

  // 处理上传
  const handleUpload = async () => {
    if (!file) {
      setUploadStatus('请选择要上传的文件');
      return;
    }

    if (!title) {
      setUploadStatus('请输入视频标题');
      return;
    }

    try {
      setUploadStatus('上传中...');
      setUploadProgress(0);
      setIsPaused(false);

      // 创建取消令牌
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      setUploadCancelToken(source);

      const formData = new FormData();
      formData.append('file', file);
      formData.append('title', title);
      formData.append('fileName', file.name);
      formData.append('fileSize', file.size);
      formData.append('fileType', file.type);

      // 如果是断点续传，添加偏移量
      if (resumeData) {
        formData.append('offset', resumeData.offset);
      }

      if (cover) {
        formData.append('cover', cover);
      }

      const response = await axios.post('http://localhost:3005/api/jjk/shi', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          // 如果上传已暂停，不更新进度
          if (isPaused) return;

          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          setUploadProgress(percentCompleted);
        },
        timeout: 60000,
        withCredentials: true,
        cancelToken: source.token // 关联取消令牌
      });

      setUploadStatus('上传成功！');
      console.log('上传成功:', response.data);
      // 重置表单
      resetForm();
    } catch (error) {
      if (axios.isCancel(error)) {
        // 处理取消上传的情况
        setUploadStatus('上传已暂停');
        // 保存当前进度用于续传
        setResumeData({
          offset: uploadProgress * file.size / 100
        });
      } else {
        setUploadStatus(`上传失败: ${error.message}`);
        console.error('上传错误:', error);
      }
    }
  };

  // 暂停上传
  const handlePauseUpload = () => {
    if (uploadCancelToken) {
      uploadCancelToken.cancel('上传已暂停');
      setIsPaused(true);
    }
  };

  // 继续上传
  const handleResumeUpload = () => {
    if (isPaused) {
      handleUpload(); // 重新调用上传函数
    }
  };

  // 重置表单
  const resetForm = () => {
    setFile(null);
    setTitle('');
    setCover(null);
    setUploadProgress(0);
    setUploadStatus('');
    setIsPaused(false);
    setUploadCancelToken(null);
    setResumeData(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
    if (coverInputRef.current) coverInputRef.current.value = '';
  };

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
      {/* 标题区域 */}
      <h2 style={{ textAlign: 'center', marginBottom: '30px', fontSize: '24px', fontWeight: 'bold' }}>发布视频</h2>

      {/* 加载状态 */}
      {id && !videoData && (
        <div>加载中...</div>
      )}

      {/* 视频数据不存在或无id时显示上传表单 */}
      {(!id || !videoData) ? (
        <div>
          {/* 视频标题输入 */}
          <div style={{ marginBottom: '25px' }}>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              style={{
                width: '100%',
                padding: '12px',
                fontSize: '16px',
                border: '1px solid #e0e0e0',
                borderRadius: '4px',
                boxSizing: 'border-box'
              }}
              placeholder="输入视频标题"
            />
          </div>

          {/* 大区域上传 */}
          <div
            ref={uploadAreaRef}
            style={{
              width: '100%',
              height: '300px',
              border: `2px dashed ${isDragging ? '#4CAF50' : '#e0e0e0'}`,
              borderRadius: '8px',
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
              marginBottom: '30px',
              backgroundColor: isDragging ? 'rgba(76, 175, 80, 0.05)' : 'white',
              cursor: 'pointer',
              transition: 'all 0.3s ease'
            }}
            onClick={() => fileInputRef.current.click()}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
          >
            {/* 上传图标 */}
            <div
              style={{
                width: '80px',
                height: '80px',
                borderRadius: '50%',
                backgroundColor: '#f5f5f5',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                marginBottom: '20px'
              }}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="40"
                height="40"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#9e9e9e"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                <polyline points="7 10 12 15 17 10" />
                <line x1="12" y1="15" x2="12" y2="3" />
              </svg>
            </div>

            {/* 上传提示文字 */}
            <p style={{ fontSize: '16px', color: '#757575', margin: '0' }}>点击上传或将文件拖入此区域</p>

            {/* 隐藏的文件输入 */}
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              style={{ display: 'none' }}
              accept="video/*"
            />
          </div>

          {/* 已选择文件信息 */}
          {file && (
            <div style={{ marginBottom: '25px', padding: '15px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
              <p style={{ margin: '0', fontWeight: 'bold' }}>已选择: {file.name}</p>
              <p style={{ margin: '5px 0 0 0', color: '#616161' }}>文件大小: {(file.size / (1024 * 1024)).toFixed(2)} MB</p>
            </div>
          )}

          {/* 封面图片选择 */}
          <div style={{ marginBottom: '25px' }}>
            <label style={{ display: 'block', marginBottom: '10px', fontSize: '16px', fontWeight: 'bold' }}>封面图片 (可选):</label>
            <input
              type="file"
              ref={coverInputRef}
              onChange={handleCoverChange}
              style={{
                width: '100%',
                padding: '10px',
                border: '1px solid #e0e0e0',
                borderRadius: '4px',
                backgroundColor: 'white'
              }}
              accept="image/*"
            />
            {cover && <p style={{ marginTop: '10px' }}>已选择封面: {cover.name}</p>}
          </div>

          {/* 上传按钮区域 */}
          <div style={{ marginBottom: '25px', display: 'flex', gap: '10px' }}>
            <button
              onClick={handleUpload}
              style={{
                padding: '12px 24px',
                backgroundColor: '#4CAF50',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: 'pointer',
                fontSize: '16px',
                flex: '1'
              }}
              disabled={uploadProgress > 0 && uploadProgress < 100}
            >
              开始上传
            </button>

            {uploadProgress > 0 && uploadProgress < 100 && (
              <>                
                <button
                  onClick={handlePauseUpload}
                  style={{
                    padding: '12px 24px',
                    backgroundColor: '#f44336',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    fontSize: '16px',
                    flex: '1'
                  }}
                  disabled={isPaused}
                >
                  暂停上传
                </button>

                {isPaused && (
                  <button
                    onClick={handleResumeUpload}
                    style={{
                      padding: '12px 24px',
                      backgroundColor: '#2196F3',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '16px',
                      flex: '1'
                    }}
                  >
                    继续上传
                  </button>
                )}
              </>
            )}
          </div>

          {/* 上传状态和进度 */}
          {uploadStatus && (
            <div style={{ marginTop: '15px', fontSize: '16px', color: '#616161' }}>{uploadStatus}</div>
          )}

          {uploadProgress > 0 && uploadProgress < 100 && (
            <div style={{ marginTop: '10px' }}>
              <div style={{ width: '100%', backgroundColor: '#f1f1f1', borderRadius: '20px', overflow: 'hidden' }}>
                <div
                  style={{
                    width: `${uploadProgress}%`,
                    height: '10px',
                    backgroundColor: '#4CAF50',
                    transition: 'width 0.3s ease'
                  }}
                ></div>
              </div>
              <p style={{ textAlign: 'right', margin: '5px 0 0 0', fontSize: '14px', color: '#616161' }}>{uploadProgress}%</p>
            </div>
          )}

          {/* 底部推荐信息 */}
          <div style={{ marginTop: '40px', paddingTop: '20px', borderTop: '1px solid #e0e0e0', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap' }}>
            <div style={{ marginBottom: '15px', minWidth: '200px' }}>
              <p style={{ margin: '0 0 5px 0', fontWeight: 'bold', fontSize: '14px' }}>推荐尺寸</p>
              <p style={{ margin: '0', fontSize: '14px', color: '#616161' }}>16:9、18:9、21:9的横版视频</p>
              <p style={{ margin: '0', fontSize: '14px', color: '#616161' }}>9:16的竖版视频</p>
            </div>
            <div style={{ marginBottom: '15px', minWidth: '200px' }}>
              <p style={{ margin: '0 0 5px 0', fontWeight: 'bold', fontSize: '14px' }}>推荐分辨率</p>
              <p style={{ margin: '0', fontSize: '14px', color: '#616161' }}>横版视频1920*1080</p>
              <p style={{ margin: '0', fontSize: '14px', color: '#616161' }}>竖版视频720*1280</p>
            </div>
            <div style={{ marginBottom: '15px', minWidth: '200px' }}>
              <p style={{ margin: '0 0 5px 0', fontWeight: 'bold', fontSize: '14px' }}>视频大小</p>
              <p style={{ margin: '0', fontSize: '14px', color: '#616161' }}>≤ 5.32G</p>
            </div>
          </div>
        </div>
      ) : (
        // ... 保留原有的视频详情展示逻辑 ...
        <div className="video-detail">
          <div style={{ marginBottom: '15px' }}>
            <h3>{videoData.title}</h3>
          </div>

          {videoData.cover && (
            <div style={{ marginBottom: '15px' }}>
              <img
                src={videoData.cover}
                alt={videoData.title}
                style={{ maxWidth: '100%', height: 'auto' }}
              />
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default Shang; // 添加导出语句